package com.tianluo.tianluobookstore.service.impl;

import com.tianluo.tianluobookstore.UserInfoPO;
import com.tianluo.tianluobookstore.UserInfoPOExample;
import com.tianluo.tianluobookstore.domain.dto.UserInfoDTO;
import com.tianluo.tianluobookstore.domain.view.UserInfoVO;
import com.tianluo.tianluobookstore.enums.CommonCodeEnum;
import com.tianluo.tianluobookstore.enums.UserCodeEnum;
import com.tianluo.tianluobookstore.exception.BizException;
import com.tianluo.tianluobookstore.mapper.UserInfoPOMapper;
import com.tianluo.tianluobookstore.request.RegisterUserRequest;
import com.tianluo.tianluobookstore.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.print.DocFlavor;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoPOMapper userInfoPOMapper;

    @Override
    public List<UserInfoDTO> queryUserInfoList(Integer pageSize, Integer pageNum) {

//        UserInfoPOExample example = new UserInfoPOExample();
//        UserInfoPOExample.Criteria criteria = example.createCriteria();
//        criteria.andIdEqualTo(1);
//        List<UserInfoPO> userInfoPOList = userInfoPOMapper.selectByExample(example);

        Integer offset = 0;
        if (pageNum >= 1) {
            offset = (pageNum - 1) * pageSize;
        }
        LocalDate localDate = LocalDate.of(2020, 9, 5);

        ZonedDateTime zonedDateTime = localDate.atStartOfDay().atZone(ZoneId.systemDefault());

        // 将ZonedDateTime转换为java.util.Date
        Date date = Date.from(zonedDateTime.toInstant());
        List<UserInfoPO> userInfoPOList = userInfoPOMapper.pageQueryUserInfo(pageSize, offset, date);

        List<UserInfoDTO> userInfoDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userInfoPOList)) {
            for (UserInfoPO userInfoPO : userInfoPOList) {
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                BeanUtils.copyProperties(userInfoPO, userInfoDTO);
                userInfoDTOList.add(userInfoDTO);
            }
        }

        return userInfoDTOList;
    }

    @Override
    public UserInfoDTO queryUsername(String userName) {
        UserInfoPOExample example = new UserInfoPOExample();
        UserInfoPOExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(userName);
        List<UserInfoPO> userInfoPOList = userInfoPOMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(userInfoPOList)) {
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            BeanUtils.copyProperties(userInfoPOList.get(0), userInfoDTO);
            return userInfoDTO;
        }

        return null;
    }

    @Override
    public UserInfoDTO registerUser(RegisterUserRequest userRequest) {

        UserInfoPO record = new UserInfoPO();
        BeanUtils.copyProperties(userRequest, record);
        record.setVersion(1);
        //todo 目前是userId 定义为long类型的，又是唯一的，先写死，后面优化
        record.setUserId(1L);
        Date now = new Date();
        record.setRegisterDate(now);
        record.setCreatedTime(now);
        record.setUpdatedTime(now);
        record.setCreator("田螺");
        record.setModifier("田螺");
        record.setUsername(userRequest.getUserName());

        try {
            int userResult = userInfoPOMapper.insert(record);
            if (userResult <= 0) {
                throw new BizException(CommonCodeEnum.DATABASE_ERROR);
            }
        } catch (DuplicateKeyException e) {
            log.warn("注册用户唯一键冲突，userName:{}", userRequest.getUserName());
            UserInfoPOExample example = new UserInfoPOExample();
            UserInfoPOExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(userRequest.getUserName());
            List<UserInfoPO> userInfoPOList = userInfoPOMapper.selectByExample(example);

            if (!CollectionUtils.isEmpty(userInfoPOList)) {
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                BeanUtils.copyProperties(userInfoPOList.get(0), userInfoDTO);
                return userInfoDTO;
            }
            throw new BizException(UserCodeEnum.USER_NOT_FOUND);
        }

        return buildUserDTO(record);
    }

    @Override
    public UserInfoDTO queryByPhone(String phone) {
        UserInfoPOExample example = new UserInfoPOExample();
        UserInfoPOExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneNumberEqualTo(phone);
        List<UserInfoPO> userInfoPOList = userInfoPOMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(userInfoPOList)) {
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            BeanUtils.copyProperties(userInfoPOList.get(0), userInfoDTO);
            return userInfoDTO;
        }

        return null;
    }

    @Override
    public UserInfoVO selectByPhone(String phone) {
        System.out.println("当前线程2" + Thread.currentThread().getName());
        UserInfoDTO userInfoDTO = this.queryByPhone(phone);
        if (Objects.nonNull(userInfoDTO)) {
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(userInfoDTO, userInfoVO);
            return userInfoVO;
        }
        return null;
    }

    private UserInfoDTO buildUserDTO(UserInfoPO record) {

      UserInfoDTO userInfoDTO = new UserInfoDTO();
      BeanUtils.copyProperties(record, userInfoDTO);
      return userInfoDTO;
    }
}
